package com.action.wx.member;

import com.alibaba.fastjson.JSONObject;
import com.bean.Mb_account;
import com.bean.Member;
import com.common.BaseAction;
import com.common.ModelAndJson;
import com.common.SystemConfig;
import com.github.pagehelper.Page;
import com.interceptor.CheckWxLogin;
import com.service.balance.BalanceRecordService;
import com.service.integral.IntegralRecordService;
import com.service.member.MbAccountService;
import com.service.member.MemberService;
import com.service.rebate.RebateService;
import com.service.wxconfig.WxConfigService;
import com.util.Config;
import com.util.HttpClient;
import com.util.StringUtil;
import com.util.wx.WXUtils;
import com.util.wx.Wx_JsApi_Sign;
import org.apache.commons.lang.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

import static org.apache.ibatis.ognl.DynamicSubscript.mid;

/**
 * 会员相关
 */
@Controller
@RequestMapping("wx/member")
public class MemberAction  extends BaseAction{

    @Autowired
    private MemberService memberService;

    @Autowired
    private WxConfigService wxConfigService;

    @Autowired
    private MbAccountService mbAccountService;

    @Autowired
    private IntegralRecordService integralRecordService;

    @Autowired
    private BalanceRecordService balanceRecordService;

    @Autowired
    private RebateService rebateService;

    @CheckWxLogin(name = "LoginCheck", failed = "/wx/loginError.htm")
    @RequestMapping("center")
    public ModelAndView center(String code,ModelMap paraMap) {
        HttpSession session = this.getSession();
        Member member=null;

        Integer mid=(Integer)session.getAttribute(SystemConfig.MemberIdSession);
        /*调试内容*/
        /*mid=9;
        member=memberService.selectByPrimaryKey(mid);
        session.setAttribute(SystemConfig.MemberIdSession,mid);
        session.setAttribute(SystemConfig.MemberSession,member);*/
        /*调试内容*/

        Mb_account account=null;
        member=(Member)session.getAttribute(SystemConfig.MemberSession);
        account = mbAccountService.selectByMemberId(mid);

        paraMap.put("mid",mid);
        paraMap.put("member",member);
        paraMap.put("account",account);
        return new ModelAndView("/wx/member/center", paraMap);
    }

    /**
     * 会员的推广统计页面
     * @param paraMap
     * @return
     */
    @CheckWxLogin(name = "LoginCheck", failed = "/wx/loginError.htm")
    @RequestMapping("myInferior")
    public ModelAndView myInferiors(ModelMap paraMap) {
        HttpSession session = this.getSession();
        Integer mid=(Integer)session.getAttribute(SystemConfig.MemberIdSession);
        int firstTotalNum=memberService.getInferiorsNumByLv(mid,1,null,null);//累计1级推广数量
        int secondTotalNum=memberService.getInferiorsNumByLv(mid,2,null,null);//累计2级推广数量
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cale = Calendar.getInstance();
        cale.set(Calendar.DAY_OF_MONTH, 1);
        String monthFirstday = format.format(cale.getTime());// 获取本月的第一天日期
        String monthStartTime=monthFirstday+" 00:00:00";

        cale = Calendar.getInstance();
        String today = format.format(cale.getTime());// 获取今天日期
        String todayStartTime=today+" 00:00:00";//今日结束时间
        String todayEndTime=today+" 23:59:59";//今日结束时间

        int firstMonthNum=memberService.getInferiorsNumByLv(mid,1,monthStartTime,todayEndTime);//本月累计1级推广数量
        int secondMonthNum=memberService.getInferiorsNumByLv(mid,2,monthStartTime,todayEndTime);//本月累计2级推广数量

        int firstTodayNum=memberService.getInferiorsNumByLv(mid,1,todayStartTime,todayEndTime);//今日累计1级推广数量
        int secondTodayNum=memberService.getInferiorsNumByLv(mid,2,todayStartTime,todayEndTime);//今日累计2级推广数量

        cale.add(Calendar.DAY_OF_MONTH,-1);
        String yestDay = format.format(cale.getTime());// /获取昨天日期
        String yestStartTime=yestDay+" 00:00:00";//昨日开始时间
        String yestEndTime=yestDay+" 23:59:59";//昨日结束时间

        int firstYestNum=memberService.getInferiorsNumByLv(mid,1,yestStartTime,yestEndTime);//昨日累计1级推广数量
        int secondYestNum=memberService.getInferiorsNumByLv(mid,2,yestStartTime,yestEndTime);//昨日累计2级推广数量

        paraMap.put("firstTotalNum",firstTotalNum);
        paraMap.put("secondTotalNum",secondTotalNum);

        paraMap.put("firstMonthNum",firstMonthNum);
        paraMap.put("secondMonthNum",secondMonthNum);

        paraMap.put("firstTodayNum",firstTodayNum);
        paraMap.put("secondTodayNum",secondTodayNum);

        paraMap.put("firstYestNum",firstYestNum);
        paraMap.put("secondYestNum",secondYestNum);

        paraMap.put("mid",mid);
        return new ModelAndView("/wx/inferior/my_inferior", paraMap);
    }

    /**
     * 会员的1级或2级推广会员列表页
     * @param modelMap
     * @param lv
     * @param pageNum
     * @param pageSize
     * @return
     */
    @CheckWxLogin(name = "LoginCheck", failed = "/wx/loginError.htm")
    @RequestMapping("inferiorList")
    public ModelAndView inferiorList(ModelMap modelMap, Integer lv, Integer pageNum, Integer pageSize) {
        HttpSession session = this.getSession();
        Integer mid=(Integer)session.getAttribute(SystemConfig.MemberIdSession);
        pageNum=pageNum==null?0:pageNum;
        pageSize=pageSize==null?10:pageSize;
        HashMap<String, Object> paraMap = new HashMap<>();
        paraMap.put("mid",mid);
        paraMap.put("lv",lv);
        Page page = memberService.findInferiorsByPage(pageNum, pageSize, paraMap);
        modelMap.put("page",page);
        modelMap.put("totalPage", page.getPages());
        modelMap.put("pageNum", pageNum);
        modelMap.put("pageSize", pageSize);
        modelMap.put("mid", mid);
        modelMap.put("lv", lv);
        return new ModelAndView("/wx/inferior/inferior_list", modelMap);
    }

    /**
     * 会员的1级或2级推广会员列表 分页
     * @param modelMap
     * @param mid
     * @param lv
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ResponseBody
    @RequestMapping("getInferiorListData")
    public String setDefault(ModelAndJson modelMap, Integer mid, Integer lv, Integer pageNum, Integer pageSize) {
        HashMap<String, Object> paraMap = new HashMap<>();
        paraMap.put("mid",mid);
        paraMap.put("lv",lv);
        Page page = memberService.findInferiorsByPage(pageNum, pageSize, paraMap);
        modelMap.put("page",page);
        modelMap.put("pages", page.getPages());
        modelMap.put("pageNum", page.getPageNum());
        modelMap.put("pageSize", page.getPageSize());
        modelMap.put("mid", mid);
        modelMap.put("lv", lv);
        modelMap.setTrue("");
        return modelMap.toString();
    }

    /**
     * 1级推广会员的推广会员列表
     * @param modelMap
     * @param pid
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping("inferiorChildList")
    public ModelAndView inferiorChildList(ModelMap modelMap, Integer pid,Integer pageNum, Integer pageSize) {
        pageNum=pageNum==null?0:pageNum;
        pageSize=pageSize==null?10:pageSize;
        HashMap<String, Object> paraMap = new HashMap<>();
        paraMap.put("mid",pid);
        paraMap.put("lv",1);
        Page page = memberService.findInferiorsByPage(pageNum, pageSize, paraMap);
        Member curMember = memberService.selectByPrimaryKey(pid);
        modelMap.put("page",page);
        modelMap.put("totalPage", page.getPages());
        modelMap.put("pageNum", pageNum);
        modelMap.put("pageSize", pageSize);
        modelMap.put("pid", pid);
        modelMap.put("lv", 1);
        modelMap.put("curMember",curMember);
        return new ModelAndView("/wx/inferior/child_list", modelMap);
    }

    /**
     * 1级推广会员的推广会员的列表   分页
     * @param modelMap
     * @param pid
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ResponseBody
    @RequestMapping("getInferiorChildListData")
    public String getInferiorChildListData(ModelAndJson modelMap, Integer pid, Integer pageNum, Integer pageSize) {
        HashMap<String, Object> paraMap = new HashMap<>();
        paraMap.put("mid",pid);
        paraMap.put("lv",1);
        Page page = memberService.findInferiorsByPage(pageNum, pageSize, paraMap);
        modelMap.put("page",page);
        modelMap.put("pages", page.getPages());
        modelMap.put("pageNum", page.getPageNum());
        modelMap.put("pageSize", page.getPageSize());
        modelMap.put("mid", pid);
        modelMap.put("lv", 1);
        modelMap.setTrue("");
        return modelMap.toString();
    }

    @CheckWxLogin(name = "LoginCheck", failed = "/wx/loginError.htm")
    @RequestMapping("myIntegral")
    public ModelAndView myIntegral(ModelMap modelMap,Integer pageNum, Integer pageSize) {
        HttpSession session = this.getSession();
        Integer mid=(Integer)session.getAttribute(SystemConfig.MemberIdSession);
        pageNum=pageNum==null?0:pageNum;
        pageSize=pageSize==null?10:pageSize;
        Mb_account mb = mbAccountService.selectByMemberId(mid);
        HashMap<String, Object> paraMap = new HashMap<>();
        paraMap.put("mid",mid);
        Page page = integralRecordService.findRecordByPage(pageNum,pageSize,paraMap);
        modelMap.put("account",mb);
        modelMap.put("mid",mid);
        modelMap.put("page",page);
        modelMap.put("totalPage", page.getPages());
        modelMap.put("pageNum", pageNum);
        modelMap.put("pageSize", pageSize);
        return new ModelAndView("/wx/integral/my_integral", modelMap);
    }

    @ResponseBody
    @RequestMapping("myIntegralData")
    public String myIntegralData(ModelAndJson modelMap, Integer mid, Integer pageNum, Integer pageSize) {
        HashMap<String, Object> paraMap = new HashMap<>();
        paraMap.put("mid",mid);
        Page page = integralRecordService.findRecordByPage(pageNum,pageSize,paraMap);
        modelMap.put("page",page);
        modelMap.put("totalPage", page.getPages());
        modelMap.put("pageNum", pageNum);
        modelMap.put("pageSize", pageSize);
        modelMap.put("mid", mid);
        modelMap.setTrue("");
        return modelMap.toString();
    }

    @CheckWxLogin(name = "LoginCheck", failed = "/wx/loginError.htm")
    @RequestMapping("myBalance")
    public ModelAndView myBalance(ModelMap modelMap,Integer pageNum, Integer pageSize) {
        HttpSession session = this.getSession();
        Integer mid=(Integer)session.getAttribute(SystemConfig.MemberIdSession);
        pageNum=pageNum==null?0:pageNum;
        pageSize=pageSize==null?10:pageSize;
        Mb_account mb = mbAccountService.selectByMemberId(mid);
        HashMap<String, Object> paraMap = new HashMap<>();
        paraMap.put("mid",mid);
        Page page = balanceRecordService.findRecordByPage(pageNum,pageSize,paraMap);
        modelMap.put("account",mb);
        modelMap.put("mid",mid);
        modelMap.put("page",page);
        modelMap.put("totalPage", page.getPages());
        modelMap.put("pageNum", pageNum);
        modelMap.put("pageSize", pageSize);
        return new ModelAndView("/wx/balance/my_balance", modelMap);
    }

    @CheckWxLogin(name = "LoginCheck", failed = "/wx/loginError.htm")
    @ResponseBody
    @RequestMapping("myBalanceData")
    public String myBalanceData(ModelAndJson modelMap, Integer mid, Integer pageNum, Integer pageSize) {
        HashMap<String, Object> paraMap = new HashMap<>();
        paraMap.put("mid",mid);
        Page page = balanceRecordService.findRecordByPage(pageNum,pageSize,paraMap);
        modelMap.put("page",page);
        modelMap.put("totalPage", page.getPages());
        modelMap.put("pageNum", pageNum);
        modelMap.put("pageSize", pageSize);
        modelMap.put("mid", mid);
        modelMap.setTrue("");
        return modelMap.toString();
    }

    @CheckWxLogin(name = "LoginCheck", failed = "/wx/loginError.htm")
    @RequestMapping("myRebate")
    public ModelAndView myRebate(ModelMap modelMap,Integer pageNum, Integer pageSize) {
        HttpSession session = this.getSession();
        Integer mid=(Integer)session.getAttribute(SystemConfig.MemberIdSession);
        pageNum=pageNum==null?0:pageNum;
        pageSize=pageSize==null?10:pageSize;
        Mb_account mb = mbAccountService.selectByMemberId(mid);
        HashMap<String, Object> paraMap = new HashMap<>();
        paraMap.put("mid",mid);
        Page page = rebateService.findRecordByPage(pageNum,pageSize,paraMap);
        modelMap.put("account",mb);
        modelMap.put("mid",mid);
        modelMap.put("page",page);
        modelMap.put("totalPage", page.getPages());
        modelMap.put("pageNum", pageNum);
        modelMap.put("pageSize", pageSize);
        return new ModelAndView("/wx/rebate/my_rebate", modelMap);
    }

    @CheckWxLogin(name = "LoginCheck", failed = "/wx/loginError.htm")
    @ResponseBody
    @RequestMapping("myRebateData")
    public String myRebateData(ModelAndJson modelMap, Integer mid, Integer pageNum, Integer pageSize) {
        HashMap<String, Object> paraMap = new HashMap<>();
        paraMap.put("mid",mid);
        Page page = rebateService.findRecordByPage(pageNum,pageSize,paraMap);
        modelMap.put("page",page);
        modelMap.put("totalPage", page.getPages());
        modelMap.put("pageNum", pageNum);
        modelMap.put("pageSize", pageSize);
        modelMap.put("mid", mid);
        modelMap.setTrue("");
        return modelMap.toString();
    }

    /**
     *  修改会员信息(lv)
     * @param modelMap
     * @return
     */
    @CheckWxLogin(name = "LoginCheck", failed = "/wx/loginError.htm")
    @RequestMapping("editMemberInfo")
    public ModelAndView editMemberInfo(ModelMap modelMap, HttpServletRequest request){
        String url = request.getRequestURL().toString();
        Wx_JsApi_Sign wxJsApiSign = WXUtils.getSign(url);
        HttpSession session = this.getSession();
        Integer mid=(Integer)session.getAttribute(SystemConfig.MemberIdSession);
        Member member = memberService.selectByPrimaryKey(mid);
        modelMap.put("member",member);
        modelMap.put("wxJsApiSign",wxJsApiSign);
        return new ModelAndView("/wx/member/edit_member_info",modelMap);
    }

    /**
     *  保存修改会员信息(lv)
     * @param modelMap
     * @return
     */
    @CheckWxLogin(name = "LoginCheck", failed = "/wx/loginError.htm")
    @RequestMapping("saveMemberInfo")
    @ResponseBody
    public String saveMemberInfo(ModelAndJson modelMap,String nickname,String headimg){
        HttpSession session = this.getSession();
        Integer mid=(Integer)session.getAttribute(SystemConfig.MemberIdSession);
        Member mb = memberService.selectByPrimaryKey(mid);
        if(StringUtil.isNotEmpty(nickname)){
            mb.setNickname(nickname);
        }
        if(StringUtil.isNotEmpty(headimg)){
            mb.setHeadimg(headimg);
        }
        int i = memberService.updateByPrimaryKeySelective(mb);
        if(i>0){
            modelMap.setTrue("保存成功");
        }
        return modelMap.toString();
    }

    @CheckWxLogin(name = "LoginCheck", failed = "/wx/loginError.htm")
    @RequestMapping("goCharge")
    public ModelAndView goCharge(ModelMap modelMap) {
        HttpSession session = this.getSession();
        Integer mid=(Integer)session.getAttribute(SystemConfig.MemberIdSession);
        Member member = memberService.selectByPrimaryKey(mid);
        Mb_account mb = mbAccountService.selectByMemberId(mid);
        HashMap<String, Object> paraMap = new HashMap<>();
        paraMap.put("mid",mid);
        modelMap.put("account",mb);
        modelMap.put("member",member);
        modelMap.put("mid",mid);
        return new ModelAndView("/wx/member/charge", modelMap);
    }


    @CheckWxLogin(name = "LoginCheck", failed = "/wx/loginError.htm")
    @RequestMapping("myQrcode")
    public ModelAndView myQrcode(ModelMap modelMap) {
        HttpSession session = this.getSession();
        Member member=(Member)session.getAttribute(SystemConfig.MemberSession);
        String myQrcode = this.getMemberEwm(member.getOpenid());
        HashMap<String, Object> paraMap = new HashMap<>();
        modelMap.put("myQrcode", myQrcode);
        modelMap.put("member", member);
        return new ModelAndView("/wx/member/my_qrcode", modelMap);
    }


    public String getMemberEwm(String openId){
        Member member = memberService.getMeberByOpenId(openId);
        if(member==null) {
            return null;
        }
        String myQrcode = member.getExtcode();
        if(StringUtils.isNotBlank(myQrcode)){
            //new Date().getTime()
            long lang =System.currentTimeMillis()  - member.getExtinvalidtime().getTime();
            if(lang<604800){
                    return myQrcode;
            }
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("expire_seconds", 604800);//7天
        jsonObject.put("action_name", "QR_SCENE");//临时二维码
        JSONObject jsObject = new JSONObject();
        jsObject.put("scene_id", member.getId());

        JSONObject jsob=new JSONObject();
        jsob.put("scene", jsObject.toString());

        jsonObject.put("action_info", jsob.toString());

        String json=jsonObject.toString();
            String appid = Config.getString("wx.appid");
            String appsecret = Config.getString("wx.appsecret");
            String token = wxConfigService.getAccessToken(appid, appsecret);
            String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=ACCESS_TOKEN";
            url = url.replace("ACCESS_TOKEN", token);
            JSONObject rt = HttpClient.httpRequest(url,"POST",json);
            String ticket = (String) rt.get("ticket");
            if (StringUtils.isBlank(ticket)) {
             return "";
            }
                url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET";
                String result = url.replace("TICKET", ticket);
                member.setExtcode(result);
                member.setExtinvalidtime(new Date());
                memberService.updateByPrimaryKey(member);
                return result;

    }
}
